package backing;

import hibernate.HibernateUtil;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import model.Book;
import model.Category;
import model.Client;
import model.Order;

import org.hibernate.Session;

@ManagedBean(name="boutiqueBacking")
@SessionScoped
public class BoutiqueBacking {
	public BoutiqueBacking(){
	}
	private Category category;
	private Book book;
	private Order order = new Order();
	private Client client = new Client();

	public Order getOrder() {
		return order;
	}

	public Client getClient() {
		return client;
	}

	public void setClient(Client client) {
		this.client = client;
	}

	public void setOrder(Order order) {
		this.order = order;
	}

	public Book getBook() {
		return book;
	}

	public void setBook(Book book) {
		this.book = book;
	}

	public Category getCategory() {
		return category;
	}

	public void setCategory(Category category) {
		this.category = category;
	}

	public List<Category> getList() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		return session.createQuery("from model.Category").list();
	}

	public List<Book> getBooks() {
		return category.getBooks();
	}

	 public String selectCategory(String id) {
	    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
	    category = (Category) session.get(model.Category.class, new Long(id));
	    return "category";
	  }
	 
	 public String selectBook(String id) {
		    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		    book = (Book) session.get(model.Book.class, new Long(id));
		    return "book";
		  }

	 public void paintBookPhoto(OutputStream output, Object object) throws IOException {
		 if (book != null) {
			 output.write(book.getPhoto());
		 }
	 }
	 
	 public String addBook(String id) {
		 order.addOne(book);
		 return null;
	 }

	 
	 public String connect() {
		 Session session = HibernateUtil.getSessionFactory().getCurrentSession();
         client = (Client) session.createQuery("from model.Client where login = :login and password = :password")	
                 .setString("login", client.getLogin()).setString("password", client.getPassword()).uniqueResult();
         if (client!=null) {
        	 return "welcome";
         } else {
        	 FacesMessage message = new FacesMessage();
        	 message.setSeverity(FacesMessage.SEVERITY_ERROR);
        	 message.setSummary("L'indentification n'est pas correcte");
        	 message.setDetail("Corrigez le login ou le mot de passe.");
        	 FacesContext context = FacesContext.getCurrentInstance();
        	 context.addMessage(null, message);
        	 return null;
         }
	 }
}
